package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1049 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 不是因为复杂，而是因为经典
     * 未来需要再次复习此道题目
     * 经典的0-1背包，就是问题转化比较难想
     * @return:
     */
    class Solution {
        public int lastStoneWeightII(int[] stones) {
            int n = stones.length;
            int sum = 0;
            for (int num : stones) {
                sum += num;
            }
            //背包容量上限为石头总重量的一半
            int dp[][] = new int[n + 1][sum / 2 + 1];
            for (int i = 1; i <= n; i++) {
                for (int j = 0; j <= sum / 2; j++) {
                    //当我能把这块石头放进背包时，我会比较放或不放，选择最大值
                    if (j >= stones[i - 1]) {
                        dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]);
                    } else {
                        //这块石头放不进背包时，只能跳过
                        dp[i][j] = dp[i - 1][j];
                    }
                }
            }
            //dp[n][sum/2]的最大值为sum/2，因此最理想的结果为0
            return sum - dp[n][sum / 2] * 2;
        }
    }

    public void run() {
        int[] arr = InputUtil.toIntegerArray("[1,2,3]");
        System.out.println(new Solution().toString());
    }

    public static void main(String[] args) throws Exception {
        LC1049 an = new LC1049();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
